package cn.mofuxiong.Filter.LoginFileter;




import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {
	private String excludedPages;
	private String[] excludedPageArray;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException 
	{
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		String UserId = null;
		String basePath=req.getContextPath();
		String uri = req.getRequestURI();
		boolean if_return=false;
		
		/*查看请求的url是否包含配置文件*/
		for(int i = 0;i<excludedPageArray.length;i++)
		{
			if(uri.contains(excludedPageArray[i]))
			{
				if_return=true;
				break;
			}
		}
		
		if(if_return)
		{
			chain.doFilter(request, response);
		}
		else if(if_return==false)
		{
			if(session.getAttribute("UserId")!= null)
			{
				chain.doFilter(request, response);
			}
			else
			{
				resp.sendRedirect(basePath+"/Login/login.jsp?msg=-1");
			}
		}
		
		

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException 
	{
		//读取web.xml文件 name为excludedPages 的配置项，得到的是一个string，再用，分割成数组
		ServletContext sc = filterConfig.getServletContext();
		excludedPages = sc.getInitParameter("excludedPages");
		if (excludedPages != null)
			excludedPageArray = excludedPages.split(",");
		return;
	}

}
